using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebUpdaterAdminCore.Data;
using Z.EntityFramework.Plus;

namespace WebUpdaterAdminCore.Utils
{
    public  static partial class Utils
    {
        public static IWebHost SocketPrepare(this IWebHost webHost)
        {
            var  serviceScopeFactory = (IServiceScopeFactory)webHost.Services.GetService(typeof(IServiceScopeFactory));
            using(var scope = serviceScopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;
                var dbContext = services.GetRequiredService<ApplicationDbContext>();
                //初始分组数据
                var defaultGroup = dbContext.ClientGroups.Where(w => w.Name == "默认").FirstOrDefault();
                if(defaultGroup == null)
                {
                    defaultGroup = new Models.ClientGroup
                    {
                        Id = 0,
                        Name = "默认"
                    };
                    dbContext.ClientGroups.Add(defaultGroup);
                    dbContext.SaveChanges();
                }
                //服务端启动时,设置客户端连接状态为false

                var count = dbContext.ClientStatus.Where(w => w.Connected).Update(x => new Models.ClientState { Connected = false });
              

                var socketSvc = webHost.Services.GetService<UpdaterSocketServerService>();
                socketSvc.SetDbContext(serviceScopeFactory);
            }
            
            return webHost;
        }

        
    }
}
